<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容"
                    class="input-with-select"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="isDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList"
                stripe
                border>
        <el-table-column label="ID"
                         type="index"></el-table-column>
        <el-table-column label="姓名"
                         prop="username"></el-table-column>
        <el-table-column label="邮箱"
                         prop="email"></el-table-column>
        <el-table-column label="电话"
                         prop="mobile"></el-table-column>
        <el-table-column label="角色"
                         prop="role_name">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="updateState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-edit"
                       @click="editUserDialog(scope.row.id)"></el-button>
            <el-button size="mini"
                       type="danger"
                       icon="el-icon-delete"
                       @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top">
              <el-button size="mini"
                         type="warning"
                         icon="el-icon-setting"
                         @click="setUserRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pagenum"
                     :page-sizes="[5, 10, 15, 20]"
                     :page-size="5"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <el-dialog title="添加用户"
                 :visible.sync="isDialogVisible"
                 width="50%"
                 @close="addDialogClose">
        <el-form ref="addUserFromRef"
                 :model="addUserFrom"
                 :rules="addUserFromRules"
                 label-width="70px">
          <el-form-item label="用户名"
                        prop="username">
            <el-input v-model="addUserFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="addUserFrom.password"
                      show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="addUserFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="addUserFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="isDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="编辑用户"
                 :visible.sync="isEditDialog"
                 width="50%"
                 @close="editDialogClose">
        <el-form ref="editUserFromRef"
                 :model="editUserFrom"
                 :rules="editUserFromRules"
                 label-width="70px">
          <el-form-item label="用户名"
                        prop="username">
            <el-input v-model="editUserFrom.username"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="editUserFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="editUserFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="isEditDialog = false">取 消</el-button>
          <el-button type="primary"
                     @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="分配角色"
                 :visible.sync="isSetDialogVisible"
                 width="50%"
                 @close="setDiologClose">
        <p>当前的用户:{{this.userInfo.username}}</p>
        <p>当前的角色:{{this.userInfo.role_name}}</p>
        <p>分配新角色: <el-select v-model="selectedRoleId"
                     placeholder="请选择">
            <el-option v-for="item in roleList"
                       :key="item.id"
                       :label="item.roleName"
                       :value="item.id">
            </el-option>
          </el-select>
        </p>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="isSetDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="setUserRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Users",
  data () {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

      if (regEmail.test(value)) return callback()

      callback(new Error('请输入正确的邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1\d{10}$/

      if (regMobile.test(value)) return callback()

      callback(new Error('请输入正确的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      userList: [],
      isDialogVisible: false,
      addUserFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFromRules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      isEditDialog: false,
      editUserFrom: {},
      editUserFromRules: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      userInfo: {},
      isSetDialogVisible: false,
      roleList: {},
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.total = res.data.total
      this.userList = res.data.users
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async updateState (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },
    addDialogClose () {
      this.$refs.addUserFromRef.resetFields()
    },
    addUser () {
      this.$refs.addUserFromRef.validate(async vaild => {
        if (!vaild) return

        const { data: res } = await this.$http.post('users', this.addUserFrom)
        if (res.meta.status !== 201) this.$message.error('用户添加失败')
        this.$message.success('用户添加成功')

        this.isDialogVisible = false

        this.getUserList()
      })
    },
    async editUserDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('用户信息获取失败')
      this.editUserFrom = res.data
      this.isEditDialog = true
    },
    editDialogClose () {
      this.$refs.editUserFromRef.resetFields()
    },
    editUser () {
      this.$refs.editUserFromRef.validate(async vaild => {
        if (!vaild) return

        const { data: res } = await this.$http.put('users/' + this.editUserFrom.id, { email: this.editUserFrom.email, mobile: this.editUserFrom.mobile })
        if (res.meta.status !== 200) this.$message.error('更新失败')
        this.$message.success('更新成功')

        this.isEditDialog = false

        this.getUserList()
      })
    },
    async deleteUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if ('cancel' === confirmResult) return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('用户删除失败')

      this.$message.success('删除成功')

      this.getUserList()
    },
    async setUserRoleDialog (info) {
      this.userInfo = info
      //获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('角色列表获取失败')
      }
      this.roleList = res.data
      this.isSetDialogVisible = true
    },
    async setUserRole () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('角色分配失败')
      }

      console.log(this.userList);
      this.getUserList()
      console.log(this.userList);
      this.$message.success('角色分配成功')
      this.isSetDialogVisible = false
    },
    setDiologClose () {
      this.selectedRoleId = '',
        this.userInfo = {}
    }
  }
}
</script>

<style scoped>
</style>
